import axios from 'axios';
import proxyService from './proxyService';

interface ChatMessage {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

interface ChatRequest {
  model: string;
  messages: ChatMessage[];
  stream?: boolean;
  options?: Record<string, any>;
}

interface ModelInfo {
  name: string;
  modified_at: string;
  size: number;
  digest: string;
  details: Record<string, any>;
}

class OllamaService {
  private baseUrl: string;
  private useProxy: boolean;

  constructor() {
    // 从代理服务获取基础URL和是否使用代理
    this.baseUrl = proxyService.getBaseUrl();
    this.useProxy = proxyService.getUseProxy();
    console.log('初始化Ollama服务，使用URL:', this.getEffectiveUrl());
  }

  setBaseUrl(url: string) {
    this.baseUrl = url;
    proxyService.setBaseUrl(url);
    console.log('设置Ollama服务URL为:', url);
  }

  getBaseUrl(): string {
    return this.baseUrl;
  }

  setUseProxy(use: boolean): void {
    this.useProxy = use;
    proxyService.setUseProxy(use);
    console.log('Ollama服务代理设置为:', use ? '启用' : '禁用');
  }

  getUseProxy(): boolean {
    return this.useProxy;
  }

  getEffectiveUrl(): string {
    return proxyService.getEffectiveUrl();
  }

  async getModels(): Promise<ModelInfo[]> {
    try {
      const effectiveUrl = this.getEffectiveUrl();
      console.log('获取模型列表，URL:', `${effectiveUrl}/api/tags`);
      const response = await axios.get(`${effectiveUrl}/api/tags`);
      console.log('模型列表响应:', response.data);
      return response.data.models || [];
    } catch (error) {
      console.error('获取模型列表失败:', error);
      throw error;
    }
  }

  async streamChat(request: ChatRequest, onChunk: (text: string) => void, onComplete: () => void): Promise<void> {
    try {
      const effectiveUrl = this.getEffectiveUrl();
      console.log('发送流式聊天请求:', request);
      console.log('请求URL:', `${effectiveUrl}/api/chat`);
      
      const response = await fetch(`${effectiveUrl}/api/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ ...request, stream: true }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      if (!response.body) {
        throw new Error('Response body is null');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      
      const processChunks = async () => {
        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) {
              onComplete();
              break;
            }
            
            const chunk = decoder.decode(value, { stream: true });
            try {
              const lines = chunk.split('\n').filter(line => line.trim());
              for (const line of lines) {
                console.log('收到的数据行:', line);
                const json = JSON.parse(line);
                if (json.message?.content) {
                  onChunk(json.message.content);
                }
              }
            } catch (e) {
              console.error('解析数据块错误:', e);
            }
          }
        } catch (error) {
          console.error('处理流数据错误:', error);
        }
      };

      processChunks();
    } catch (error) {
      console.error('聊天流请求错误:', error);
      throw error;
    }
  }

  async chat(request: ChatRequest): Promise<string> {
    try {
      const effectiveUrl = this.getEffectiveUrl();
      console.log('发送普通聊天请求:', request);
      console.log('请求URL:', `${effectiveUrl}/api/chat`);
      
      const response = await axios.post(`${effectiveUrl}/api/chat`, {
        ...request,
        stream: false
      });
      return response.data.message.content;
    } catch (error) {
      console.error('聊天请求错误:', error);
      throw error;
    }
  }
}

export const ollamaService = new OllamaService();
export type { ChatMessage, ChatRequest, ModelInfo }; 